package com.hioove.netty;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * Created by RoyDeng on 17/7/20.
 */
@Slf4j
public class HttpServer {

    private final int port;

    public HttpServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
            log.error(HttpServer.class.getSimpleName());
            return;
        }
        int port = Integer.parseInt(args[0]);
        log.info("*******start********" + "http://localhost" + File.pathSeparator + port);
        new HttpServer(port).start();
    }

    public void start() throws Exception {
        ServerBootstrap b = new ServerBootstrap();
        EventLoopGroup acceptorLoopGroup = new NioEventLoopGroup(1);
        EventLoopGroup handlerLoopGroup = new NioEventLoopGroup(99);
        b.group(acceptorLoopGroup, handlerLoopGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128) // determining the number of connections queued
                .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        log.info("Handler: " + ch );
                        byte[] contant = "我是中国人！！！".getBytes(StandardCharsets.UTF_8);
                        ch.pipeline()
                                .addLast("decoder", new HttpRequestDecoder())   // 1
                                .addLast("encoder", new HttpResponseEncoder())  // 2
                                .addLast("aggregator", new HttpObjectAggregator(contant.length))    // 3
                                .addLast("handler", new HttpHandler(contant));        // 4
                    }
                });
        ChannelFuture sync = b.bind(port).sync();
        sync.channel().closeFuture().sync();
    }
}

